import 'dart:async';

import 'package:color_dart/color_dart.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:im_flutter_sdk_example/components/a_button/index.dart';
import 'package:im_flutter_sdk_example/utils/global.dart';
import 'package:shared_preferences/shared_preferences.dart';

class LoginRegiste extends StatefulWidget {
  LoginRegiste({Key key}) : super(key: key);

  _LoginMailState createState() => _LoginMailState();
}

class _LoginMailState extends State<LoginRegiste> {
  static Map phoneNumber = {"value": null, "verify": true};
  static Map passwd = {"value": null, "verify": true};
  static Map message = {"value": null, "verify": true};
  // phoneNumber vcode message  type  1[个人注册]

  SharedPreferences prefs;

  /// 开始倒计时 时间
  int startTime;

  /// 当前倒计时 时间
  int countDownTime = 0;

  /// 总倒计时时长
  final int speed = 60;

  Timer _timer;

  @override
  void initState() {
    super.initState();

    Future.delayed(Duration.zero, () async {
      prefs = await SharedPreferences.getInstance();
      startTime = prefs.getInt('startTime');
      int nowTime = G.getTime();
      if (startTime != null && startTime > 0) {
        if (nowTime - startTime > 60) {
          prefs.remove('startTime');
        } else {
          countDown();
        }
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    _timer?.cancel();
  }

  /// 获取验证码
  getEmailCode() async {
    try {
      var res =
          await G.req.user.sendMessage(telephoneNumber: phoneNumber['value']);
      if (res.data == null) return;
      G.toast('获取验证码成功');
      startTime = G.getTime();
      countDown();
    } catch (e) {
      G.toast('获取验证码失败');
    }
  }

  /// 倒计时
  countDown() {
    _timer = Timer.periodic(Duration(seconds: 1), (timer) async {
      int nowTime = G.getTime();
      int result = speed - (nowTime - startTime);
      if (result < 0) {
        prefs.remove('startTime');
        _timer?.cancel();
      }

      setState(() {
        countDownTime = result;
      });
    });
  }

  /// 注册
  _handleRegiste() async {
    if (!phoneNumber['verify'] || phoneNumber['value'] == null) {
      return G.toast('输入手机号有误');
    }
    if (!message['verify'] || message['value'] == null) {
      return G.toast('验证码不正确');
    }
    if (!passwd['verify'] || passwd['value'] == null) {
      return G.toast('密码不能为空');
    }
    print("phoneNumber: ${phoneNumber['value']}");
    print("passwd: ${passwd['value']}");
    print("message: ${message['value']}");

    /// 登录前移除user， 不然登录会提示token错误
    prefs.remove('user');
    try {
      var res = await G.req.user.register(
          phoneNumber: phoneNumber['value'],
          passwd: passwd['value'],
          message: message['value']);
      var data = res.data;
      if (data == null) return null;
      await G.toast('注册成功');
      G.pushNamed('/login_password');
    } catch (e) {
      G.toast('登录失败');
    }
  }

  getUserDetail(String token) async {
    var res = await G.req.user.detail();
    var data = res.data;
    Map json = data['data']['base'];
    json['token'] = token;
    G.user.init(json);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: customAppbar(context: context, borderBottom: false),
      body: Container(
        color: hex('#fff'),
        padding: EdgeInsets.only(left: 35, right: 35, top: 20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text('注册账号',
                style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold)),
            // Padding(
            //   padding: const EdgeInsets.symmetric(vertical: 9),
            //   child: Text('您的微信账号 XXX 通过验证',
            //       style: TextStyle(fontSize: 15, color: rgba(51, 51, 51, 1))),
            // ),
            // Text('绑定手机号，可同步第三方账号与手机号信息。经纪人不会看的您的手机号',
            //     style: TextStyle(fontSize: 12, color: rgba(191, 191, 191, 1))),
            Container(
              height: 55,
              margin: EdgeInsets.only(top: 20),
              decoration: BoxDecoration(border: G.borderBottom()),
              child: TextField(
                keyboardType: TextInputType.phone,
                decoration: InputDecoration(
                    counterText: "",
                    border: InputBorder.none,
                    hintText: '输入手机号',
                    hintStyle: TextStyle(
                      color: rgba(163, 163, 163, 1),
                      fontSize: 16,
                    )),
                onChanged: (e) {
                  RegExp regExp = RegExp(r"^1[0-9]{10}$");
                  setState(() {
                    phoneNumber['value'] = e;
                    phoneNumber['verify'] = regExp.hasMatch(e);
                  });
                },
              ),
            ),
            // Container(
            //   height: 55,
            //   decoration: BoxDecoration(border: G.borderBottom()),
            //   child: Row(
            //     children: <Widget>[
            //       Flexible(
            //         child: TextField(
            //           // maxLength: 4,
            //           keyboardType: TextInputType.text,
            //           decoration: InputDecoration(
            //               counterText: '',
            //               border: InputBorder.none,
            //               hintText: '输入图形验证码',
            //               hintStyle: TextStyle(
            //                 color: rgba(163, 163, 163, 1),
            //                 fontSize: 16,
            //               )),
            //           onChanged: (e) {
            //             setState(() {
            //               vcode['value'] = e;
            //               vcode['verify'] = e.length == 4 ? true : false;
            //             });
            //           },
            //         ),
            //       ),
            //       Container(
            //         height: 25,
            //         decoration: BoxDecoration(
            //             border: Border(
            //                 left: BorderSide(color: rgba(242, 242, 242, 1)))),
            //       ),
            //       Captcha()
            //     ],
            //   ),
            // ),
            Row(
              children: <Widget>[
                Flexible(
                  child: TextField(
                    // maxLength: 400,
                    keyboardType: TextInputType.number,
                    decoration: InputDecoration(
                        counterText: '',
                        border: InputBorder.none,
                        hintText: '输入验证码',
                        hintStyle: TextStyle(
                          color: rgba(163, 163, 163, 1),
                          fontSize: 16,
                        )),
                    onChanged: (e) {
                      setState(() {
                        message['value'] = e;
                        message['verify'] = e.length != 0 ? true : false;
                      });
                    },
                  ),
                ),
                Container(
                  height: 25,
                  decoration: BoxDecoration(
                      border: Border(
                          left: BorderSide(color: rgba(242, 242, 242, 1)))),
                ),
                buildGetEmailCode()
              ],
            ),
            Container(
              height: 55,
              margin: EdgeInsets.only(top: 20),
              decoration: BoxDecoration(border: G.borderBottom()),
              child: TextField(
                keyboardType: TextInputType.phone,
                decoration: InputDecoration(
                    counterText: "",
                    border: InputBorder.none,
                    hintText: '输入新密码',
                    hintStyle: TextStyle(
                      color: rgba(163, 163, 163, 1),
                      fontSize: 16,
                    )),
                onChanged: (e) {
                  setState(() {
                    passwd['value'] = e;
                    passwd['verify'] = true;
                  });
                },
              ),
            ),

            /// 协议
            Container(
              width: double.infinity,
              margin: EdgeInsets.only(top: 10),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                  Text(
                    '点击确定，即表示以阅读并同意',
                    style:
                        TextStyle(fontSize: 12, color: rgba(153, 153, 153, 1)),
                  ),
                  GestureDetector(
                    onTap: () => {
                      Navigator.pushNamed(context, '/user_agreement'),
                    },
                    child: Container(
                        child: Text.rich(TextSpan(children: [
                      TextSpan(
                          text: '《隐私政策》',
                          style: TextStyle(
                              fontSize: 12, color: rgba(25, 109, 236, 1))),
                      TextSpan(
                          text: '及',
                          style: TextStyle(
                              fontSize: 12, color: rgba(51, 51, 51, 1))),
                      TextSpan(
                          text: '《服务协议》',
                          style: TextStyle(
                              fontSize: 12, color: rgba(25, 109, 236, 1)))
                    ]))),
                  )
                ],
              ),
            ),

            /// 确认
            Container(
              margin: EdgeInsets.only(top: 25),
              child: AButton.normal(
                  width: double.infinity,
                  child: Text('注册'),
                  color: hex('#fff'),
                  bgColor: rgba(42, 125, 250, 1),
                  borderColor: rgba(136, 175, 213, 1),
                  onPressed: _handleRegiste),
            ),
          ],
        ),
      ),
    );
  }

  /// 获取验证码
  Container buildGetEmailCode() {
    return Container(
      child: AButton.normal(
          child: Text(countDownTime <= 0
              ? "获取验证码"
              : countDownTime < 10
                  ? '0$countDownTime s'
                  : '$countDownTime s'),
          color: message['verify'] && message['value'] != null
              ? rgba(25, 109, 236, 1)
              : rgba(166, 166, 166, 1),
          onPressed: () {
            if (countDownTime > 0) return;
            getEmailCode();
          }),
    );
  }
}
